package com.sptpc.demo1.service.impl;

import com.sptpc.demo1.model.Category;
import com.sptpc.demo1.model.Drink;
import com.sptpc.demo1.repository.CategoryRepository;
import com.sptpc.demo1.repository.DrinkRepository;
import com.sptpc.demo1.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class CategoryService implements ICategoryService {
    @Autowired
    private CategoryRepository categoryRepository;
    @Autowired
    private DrinkRepository  drinkRepository;
    @Override
    public List<Category> getAllCategory() {
        return categoryRepository.findAll();
    }

    @Override
    public void addNewCategory(Category category) {
        categoryRepository.save(category);
    }

    @Override
    public Category getCategoryById(Integer id) {
        return categoryRepository.findById(id).orElse(null);
    }

    @Override
    public void updateCategory(Category category) {
        categoryRepository.save(category);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)//表明该方法需要事务处理（事务处理即所有sql语句都需要执行，错误一个都不行）
    public void delCategory(Integer id) {
        //1. 查询所有category关联的drink
        //1.1 通过category_id把所有drink查询出来
        List<Drink> drinks=drinkRepository.findDrinkByCategory_Id(id);
        for (Drink drink : drinks) {
            //1.2 把这些drink的category设置为null
            drink.setCategory(null);
            //1.3 保存
            drinkRepository.save(drink);
        }

        //1. 删除指定id的category
        categoryRepository.deleteById(id);
    }
}
